package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.io.Resources;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Override
    public PageResponse<RoleVo> findRoleVoPage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<RoleVo> roleVoPage = (Page<RoleVo>)roleMapper.findRoleVoPage(roleDto);
        return PageResponse.of(roleVoPage, RoleVo.class);
    }
    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.roleMapper(role);
    }
    @Override
    public Set<String> findCheckedResources(Long roleId) {
        return roleMapper.findCheckedResources(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)  //注意事务问题
    public Boolean updataRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        //保存中间表的数据
       if(roleDto.getCheckedResourceNos()!=null ){
           //删除此角色之前的菜单
           roleResourceMapper.deleteByRoleId(role.getId());
           List<RoleResource> collect = Arrays.stream(roleDto.getCheckedResourceNos()).map(resourceNo ->
           {
               RoleResource roleResource = new RoleResource(role.getId(), resourceNo, "0");
               return roleResource;
           }).collect(Collectors.toList());

           if(CollUtil.isNotEmpty(collect)){
               roleResourceMapper.batchInsert(collect);

           }

       }
       return true;
    }

    @Override
    public List<RoleVo> initRoles() {
      List<RoleVo> roleVos = roleMapper.findRoleVoPage(new RoleDto());
      return BeanUtil.copyToList(roleVos, RoleVo.class);
    }


}
